import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AdminService, ProblemCreateRequest } from '../../services/admin.service';

@Component({
  standalone: false,
  selector: 'app-batch-import',
  templateUrl: './batch-import.component.html',
  styleUrls: ['./batch-import.component.css']
})
export class BatchImportComponent {
  jsonInput: string = '';
  importing = false;
  error: string | null = null;
  successMessage: string | null = null;

  constructor(
    private adminService: AdminService,
    private router: Router
  ) {}

  onImport(): void {
    if (!this.jsonInput.trim()) {
      this.error = '请输入JSON数据';
      return;
    }

    try {
      const problems: ProblemCreateRequest[] = JSON.parse(this.jsonInput);
      
      if (!Array.isArray(problems)) {
        this.error = 'JSON数据必须是数组格式';
        return;
      }

      this.importing = true;
      this.error = null;
      this.successMessage = null;

      this.adminService.batchCreateProblems(problems).subscribe({
        next: (response) => {
          if (response.success && response.data) {
            this.successMessage = `成功导入 ${response.data.length} 道题目`;
            this.jsonInput = '';
            setTimeout(() => {
              this.router.navigate(['/admin']);
            }, 2000);
          } else {
            this.error = response.message || '导入失败';
          }
          this.importing = false;
        },
        error: (error) => {
          this.error = '网络错误，请稍后重试';
          this.importing = false;
          console.error('Error importing problems:', error);
        }
      });
    } catch (e) {
      this.error = 'JSON格式错误，请检查输入';
    }
  }

  loadSample(): void {
    const sampleData = [
      {
        title: "A+B Problem",
        description: "计算两个整数的和\n\n**输入格式：**\n两个整数 a 和 b，用空格分隔\n\n**输出格式：**\n输出 a+b 的结果",
        difficulty: "Easy",
        timeLimit: 1000,
        memoryLimit: 128,
        testCases: [
          {
            input: "1 2",
            expectedOutput: "3",
            isSample: true
          },
          {
            input: "10 20",
            expectedOutput: "30",
            isSample: false
          }
        ]
      },
      {
        title: "Hello World",
        description: "输出 Hello World\n\n**输出格式：**\n输出字符串 \"Hello World\"",
        difficulty: "Easy",
        timeLimit: 1000,
        memoryLimit: 128,
        testCases: [
          {
            input: "Hello World",
            expectedOutput: "Hello World",
            isSample: true
          }
        ]
      }
    ];

    this.jsonInput = JSON.stringify(sampleData, null, 2);
  }

  cancel(): void {
    this.router.navigate(['/admin']);
  }
} 